package com.ttg.common.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.PublicKey;
import java.security.Signature;

/**
 * @author huyangzou
 * @create 2020-11-20 9:48
 */
public class SecurityUtils {

    private static final String RSA_ALGORITHM = "SHA1WithRSA";

    private static final String RSA2_SHA256RSA_ALGORITHM = "SHA256WithRSA";

    private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";

    private static final String KEY_ALGORITHM = "AES";

    /**
     * MD5验签
     */
    public static boolean verifySignWithMd5(String sign, String sortedStr) {
        String shal1 = BasicUtils.SHAL1(sortedStr);
        String signStr = BasicUtils.MD5(shal1);
        return sign.equals(signStr);
    }

    /**
     * RSA验签
     */
    public static boolean verifySignWithRsa(String sign, String sortedStr, PublicKey publicKey) throws Exception {
        Signature signature;
        signature = Signature.getInstance(RSA_ALGORITHM);
        signature.initVerify(publicKey);
        signature.update(sortedStr.getBytes(StandardCharsets.UTF_8));
        return signature.verify(BasicUtils.hex2byte(sign));
    }

    /**
     * RSA2验签
     */
    public static boolean verifySignWithRsa2(String sign, String sortedStr, PublicKey publicKey) throws Exception {
        Signature signature;
        signature = Signature.getInstance(RSA2_SHA256RSA_ALGORITHM);
        signature.initVerify(publicKey);
        signature.update(sortedStr.getBytes(StandardCharsets.UTF_8));
        return signature.verify(BasicUtils.hex2byte(sign));
    }

    /**
     * AES加密 + byte2hex
     */
    public  static String encrypt(String encryptStr, String aesKey) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(aesKey.getBytes(StandardCharsets.US_ASCII), KEY_ALGORITHM);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(1, skeySpec);
        byte[] encrypted = cipher.doFinal(encryptStr.getBytes(StandardCharsets.UTF_8));
        return BasicUtils.byte2hex(encrypted);
    }

    /**
     * AES解密 + hex2byte
     */
    public static String decrypt(String descyptStr, String aesKey) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(aesKey.getBytes(StandardCharsets.US_ASCII), KEY_ALGORITHM);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(2, skeySpec);
        byte[] encrypted = BasicUtils.hex2byte(descyptStr);
        byte[] original = cipher.doFinal(encrypted);
        return new String(original);
    }
}
